/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveNavigateToURI : CommandUtils.GrooveUtilBase
	{
		private string m_URI;

		private bool m_NewWindow;
		private bool m_Canonical;

		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveNavigateToURI(i_Arguments));
		}

		public GrooveNavigateToURI(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveNavigateToURI [PARAMS...]";
			base.HelpMessage = 
				"GrooveNavigateToURI\r\n\t" + 
				"Forces Groove to navigate to specified URI\r\n" +
				"Parameters:\r\n\t" +
				"/URI=                The URI to navigate to\r\n\t" +
				"[/NewWindow          Open a new window]\r\n\t" +
                "[/Register           Registers app as protocol handler]\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;

            bool Register = base.GetParameterValueFlag("Register");
            if (Register)
            {
                Microsoft.Win32.RegistryKey GrooveProtocolRegistryKey = null;

                try
                {
                    GrooveProtocolRegistryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("grooveProtocol");
                }
                catch (System.Exception)
                {
                }

                if (GrooveProtocolRegistryKey == null)
                {
                    GrooveProtocolRegistryKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("grooveProtocol");
                    GrooveProtocolRegistryKey.SetValue("", "URL: Groove Protocol");
                    GrooveProtocolRegistryKey.SetValue("URL Protocol", "");

                    Microsoft.Win32.RegistryKey ShellRegistrySubKey = GrooveProtocolRegistryKey.CreateSubKey("shell");
                    Microsoft.Win32.RegistryKey OpenRegistrySubKey = ShellRegistrySubKey.CreateSubKey("open");
                    Microsoft.Win32.RegistryKey CommandRegistrySubKey = OpenRegistrySubKey.CreateSubKey("command");

                    string AssemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;

                    CommandRegistrySubKey.SetValue("", AssemblyLocation + " /URI=\"%1\"");
                }

                base.StandardError.WriteLine("Registered protocol handler successfully!");
                return CommandUtils.UtilBase.CheckResult.Failed;
            }

			m_URI = base.GetParameterValue("URI");
			if (System.String.IsNullOrEmpty(m_URI))
			{
				base.DisplayUsage("You must specify a URI to navigate to.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

            if ((m_URI.IndexOf("grooveProtocol:") != -1) || (m_URI.IndexOf("grooveprotocol:") != -1))
                m_URI = m_URI.Substring("grooveProtocol:".Length);

			if ((m_URI.IndexOf("GWS/Groove") == -1) && (m_URI.IndexOf("grooveTelespace://") == -1))
			{
				base.StandardError.WriteLine("Invalid URI!");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_Canonical = (m_URI.IndexOf("GWS/Groove") == -1);

			m_NewWindow = base.GetParameterValueFlag("NewWindow");

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			if (m_Canonical)
			{
				string GrooveExecutablePath = null;
				string Arguments = null;

				try 
				{
					Microsoft.Win32.RegistryKey HKLM_GrooveRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(GrooveWebServicesV12Helpers.Shared.GROOVE_REG_KEY);

					string InstallBinRoot = (string)HKLM_GrooveRegKey.GetValue("InstallBinRoot");
					GrooveExecutablePath = InstallBinRoot + "Groove.exe";

					#region HACK ALERT:  String manipulate our way to a bindable url

					//  Sample canonical URL:
					//  "grooveTelespace://i9vrgtp8yqtiqa4k7nshbtfnyx6gfxxv3yehpmi/ToolContainer/mimd9enqbixh6/DiscussionGlue?RecordID=1555178967"

					//  Sample bindable URL:
					//  "grooveTelespace://grooveIdentity_58_47_47q7b2dsziki6bnenn4yetv5scpmfmt94n_64@i9vrgtp8yqtiqa4k7nshbtfnyx6gfxxv3yehpmi/ToolContainer/mimd9enqbixh6/DiscussionGlue?RecordID=1555178967"
					
					string ModifiedIdentityURL = base.IdentityURI.Replace("://", "_58_47_47");
					ModifiedIdentityURL = ModifiedIdentityURL.Replace("@", "_64@");

					string BindableURL = m_URI.Insert
						(
						"grooveTelespace://".Length,
						ModifiedIdentityURL
						);

					#endregion

					Arguments = System.String.Format
						(
						"/Account: {0} /URL: {1}",
						base.AccountURI,
						BindableURL
						);

				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to read registry: " + Exception.Message);
					throw Exception;
				}

				try
				{
					System.Diagnostics.Process.Start
						(
						GrooveExecutablePath,
						Arguments
						);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to navigate(2): " + Exception.Message);
					throw Exception;
				}
			}
			else
			{
				try
				{
					GrooveWebServicesV12Helpers.Local.View
						(
						base.Identity,
						m_URI,
						m_NewWindow
						);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to navigate: " + Exception.Message);
					throw Exception;
				}
			}

			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}
	}
}
